package com.cn.demo.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;

/**
 * 应用上下文工具类
 */
@Component
public class ApplicationContextUtil implements ApplicationContextAware {
    private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationContextUtil.class);
    private static ApplicationContext appCtx;

    public ApplicationContextUtil() {
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        appCtx = applicationContext;
    }

    public static ApplicationContext getCtx() {
        return appCtx;
    }

    public static Object getBean(String beanName) {
        return appCtx.getBean(beanName);
    }

    public static <T> T getBean(Class<T> type) {
        return appCtx.getBean(type);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return appCtx.getBean(name, clazz);
    }

    public static boolean isOnline() {
        return "online".equalsIgnoreCase(getCtx().getEnvironment().getProperty("local.env"));
    }

    public static void publishEvent(ApplicationEvent event) {
        try {
            appCtx.publishEvent(event);
        } catch (Exception var2) {
            LOGGER.error("publishEvent error", var2);
        }

    }

    public static void publishEvent(Object event) {
        try {
            appCtx.publishEvent(event);
        } catch (Exception var2) {
            LOGGER.error("publishEvent error", var2);
        }

    }

}
